<template>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
  >
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email" type="text" autocomplete="off"/>
    </el-form-item>

    <el-form-item label="新密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off"/>
    </el-form-item>

    <el-form-item label="验证码" prop="ver_code" style="">
      <el-input v-model="ruleForm.ver_code" type="text" autocomplete="off" style="flex: 3"/>
      <el-button type="info" style="flex: 1;margin-left: 5px" @click="sendCode1">发送验证码</el-button>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >确认修改
      </el-button
      >

      <el-button @click="resetForm(ruleFormRef)">清除</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import type {FormInstance} from 'element-plus'
import {success, error} from '../../../utils/messageUtil'
import {useRouter} from "vue-router";
import {modifyPassword, register, sendCode} from "../../../service/AccountApi";

const router = useRouter();

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('新密码不能为空'))
  } else {
    callback()
  }
}

const validateEmail = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error("邮箱不能为空"))
  } else {
    callback()
  }
}

const validateCode = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error("验证码不能为空"))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  email: '',
  ver_code: '',
  password:''
})

const sendCode1 = ()=>{
  if(ruleForm.email === ''){
    error("请先输入邮箱")
    return
  }
  const data = {
    email:ruleForm.email
  }
  sendCode(data).then(d=>{
    if(d.data.code == 200){
      success("发送成功,注意查收")
    }
  });
}

const rules = reactive({
  password: [{validator: validatePass, trigger: 'blur'}],
  email: [{validator:validateEmail, trigger: 'blur'}],
  ver_code: [{validator:validateCode, trigger: 'blur'}],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      modifyPassword(ruleForm).then(d=>{
        if(d.data.code!=200){
          error(d.data.message);
        }else{
          success("密码修改成功")
          router.push({
            name:'login'
          })
        }
      }).catch(()=>{
        error("注册失败")
      })
    } else {
      error('请检查参数')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  //清除所有东西
  formEl.resetFields()
}
</script>

<style scoped>

.el-form{
  width: 600px;
  margin: 0 auto;
}

</style>